package fr.teuteuf.runstickmanrun.screen;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Array;

import fr.teuteuf.runstickmanrun.Constants;
import fr.teuteuf.runstickmanrun.IRenderable;
import fr.teuteuf.runstickmanrun.IUpdatable;
import fr.teuteuf.runstickmanrun.entity.Player;
import fr.teuteuf.runstickmanrun.map.MapGenerator;



public abstract class AbstractGameScreen extends AbstractScreen implements ContactListener {
	
	private final int INITIAL_DISTANCE_LEVEL = 50;

	protected MapGenerator mapGenerator;
	protected World world;
	private int currentLevel;
	private int distanceNextLevel;
	
	protected Array<IUpdatable> updatables;
	protected Array<IRenderable> renderables;
	
	public abstract Player getFirstPlayer();
	public abstract World getWorld();
	
	@Override
	public void reinit() {
		world = new World(new Vector2(0, Constants.GRAVITY), true);
		world.setContactListener(this);
		
		updatables = new Array<IUpdatable>();
		renderables = new Array<IRenderable>();
		
		currentLevel = 0;
		distanceNextLevel = INITIAL_DISTANCE_LEVEL;
		for(int i = 0; i < runStickmanRun.getSelectedLevel(); i++) {
			currentLevel++;
			distanceNextLevel += (currentLevel + 1) * INITIAL_DISTANCE_LEVEL;
		}
		currentLevel = runStickmanRun.getSelectedLevel();
		mapGenerator = new MapGenerator(this, currentLevel);
		updatables.add(mapGenerator);
	}
	
	@Override
	public void update(float elapsedTime) {
		if((getFirstPlayer().getPosition().x * Constants.BOX_TO_WORLD) / 100 > distanceNextLevel && currentLevel < Constants.DIFFICULTY_MAX) {
			currentLevel++;
			distanceNextLevel += (currentLevel + 1) * INITIAL_DISTANCE_LEVEL;
			mapGenerator.changeCurrentDifficulty(currentLevel);
		}
	}
	
	@Override
	public void beginContact(Contact contact) {
	}

	@Override
	public void endContact(Contact contact) {
	}

	@Override
	public void preSolve(Contact contact, Manifold oldManifold) {
	}

	@Override
	public void postSolve(Contact contact, ContactImpulse impulse) {
	}
	
	public int getCurrentLevel() {
		return currentLevel;
	}
}
